﻿using HeBianGu.Product.UserControls.SystemKeyBoard;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;


/************************************************************************
 * 项目名称 :  TouchKeyBoard  
 * 项目描述 :     
 * 类 名 称 :  KeyBoardWindow
 * 版 本 号 :  v1.0.0.0 
 * 说    明 :     
 * 作    者 :  Lewis
 * 创建时间 :  2022/3/22 11:50:30
 * 更新时间 :  2022/3/22 11:50:30
************************************************************************/
namespace TouchKeyBoard
{
    /// <summary>
    /// KeyBoardWindow.xaml 的交互逻辑
    /// </summary>
    public partial class KeyBoardWindow : Window
    {

        public string txtValueToMain = string.Empty;

        public object inputtxt;

        public KeyBoardWindow(string Title, Type type, object txt)
        {
            InitializeComponent();
            //设置自定义距离
            var width = this.Width / 2.0;
            var height = this.Height / 2.0;
            this.ResizeMode = ResizeMode.NoResize;
            this.Left = 40;
            this.Top = (SystemParameters.PrimaryScreenHeight / 2.0)+40;
            this.Topmost = true;

            // 版本1，通过Background dispatcher
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                    (Action)(() => { 
                        Keyboard.Focus(txtValue);
                    }));

            labTitle.Content = Title;
            if (txt is null)
            {
                this.txtValue.Text = string.Empty;

            }
            else
            {
                if (type.Equals(typeof(TextBox)))
                {
                    this.txtValue.Text = ((TextBox)txt).Text;
                    txtValueToMain = ((TextBox)txt).Text;
                    inputtxt = (TextBox)txt;

                }
                else if (type.Equals(typeof(PasswordBox)))
                {
                    var len = ((PasswordBox)txt).Password.Length;
                    string str = "";

                    this.txtValue.Text = str.PadRight(len, '*'); ;
                    txtValueToMain = ((PasswordBox)txt).Password;
                    inputtxt = (PasswordBox)txt;
                }


            }
            this.btn_caps.IsChecked = Console.CapsLock;

            this.btn_caps.IsChecked = false;
            this.btn_shift.IsChecked = false;

            this.btn_caps.IsEnabled = false;
            this.btn_shift.IsEnabled = false;

            this.RefreshCaps();
        }



        
        #region 将当前窗体指定为浮动工具条窗体


        #endregion
        void RefreshCapsText()
        {
            if (this.btn_caps.IsChecked)
            {
                this.btn_caps.Content = "大写";
            }
            else
            {
                this.btn_caps.Content = "小写";
            }
        }

        private void Grid_Click(object sender, RoutedEventArgs e)
        {
            Button button = e.OriginalSource as Button;

            if (button == null) return;

            //Debug.WriteLine(button.Content);

            string content = button.Content.ToString();

            if (content == "确定")
            {
                this.OnSumitClick();
            }
            else if (content == "取消")
            {
                this.OnCancelClick();
            }
            else
            {

                //// Do ：打开大写 
                if (this.btn_shift.IsChecked)
                {
                    KeyHelper.OnKeyDown(Convert.ToByte(this.btn_shift.Tag.ToString()));
                }

                if (this.btn_shift.IsChecked)
                {
                    KeyHelper.OnKeyDown(Convert.ToByte(this.btn_shift.Tag.ToString()));
                }


                string tag = button.Tag.ToString();

                if (!tag.Equals("Enter"))
                {
                    byte b = Convert.ToByte(tag);

                    KeyHelper.OnKeyPress(b);

                }



            }
        }

        //声明和注册路由事件
        public static readonly RoutedEvent SumitClickRoutedEvent =
            EventManager.RegisterRoutedEvent("SumitClick", RoutingStrategy.Bubble,
                typeof(EventHandler<RoutedEventArgs>),
                typeof(KeyBoardWindow));
        //CLR事件包装
        public event RoutedEventHandler SumitClick
        {
            add { this.AddHandler(SumitClickRoutedEvent, value); }
            remove { this.RemoveHandler(SumitClickRoutedEvent, value); }
        }

        //激发路由事件,借用Click事件的激发方法

        protected void OnSumitClick()
        {
            RoutedEventArgs args = new RoutedEventArgs(SumitClickRoutedEvent, this);
            this.RaiseEvent(args);
        }

        //声明和注册路由事件
        public static readonly RoutedEvent CancelClickRoutedEvent =
            EventManager.RegisterRoutedEvent("CancelClick", RoutingStrategy.Bubble, typeof(EventHandler<RoutedEventArgs>),
                typeof(KeyBoardWindow));
        //CLR事件包装
        public event RoutedEventHandler CancelClick
        {
            add { this.AddHandler(CancelClickRoutedEvent, value); }
            remove { this.RemoveHandler(CancelClickRoutedEvent, value); }
        }

        //激发路由事件,借用Click事件的激发方法

        protected void OnCancelClick()
        {
            RoutedEventArgs args = new RoutedEventArgs(CancelClickRoutedEvent, this);
            this.RaiseEvent(args);
            this.Visibility = Visibility.Collapsed;
        }



        public string InputText
        {
            get { return (string)GetValue(InputTextProperty); }
            set { SetValue(InputTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty InputTextProperty =
            DependencyProperty.Register("InputText", typeof(string),
                typeof(KeyBoardWindow),
                new PropertyMetadata(default(string),
                    (d, e) =>
            {
                KeyBoardWindow control = d as KeyBoardWindow;

                if (control == null) return;

                string config = e.NewValue as string;

                //control.txt_input.Text = config;
                control.txtValue.Text = config;
            }));

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            FuncButtonControl btn = sender as FuncButtonControl;

            string tag = btn.Tag.ToString();

            byte b = Convert.ToByte(tag);

            if (btn.IsChecked)
            {
                KeyHelper.OnKeyUp(b);
            }
            else
            {
                KeyHelper.OnKeyDown(b);
            }

            btn.IsChecked = !btn.IsChecked;

        }

        void RefreshCaps()
        {


            var btns = FindVisualChild<FuncButtonControl>(this.grid_center);

            foreach (var btn in btns)
            {
                if (btn.Content == null) continue;

                if (btn.Content.ToString().Length != 1) continue;

                btn.Content = this.btn_caps.IsChecked ? btn.Content.ToString().ToUpper() : btn.Content.ToString().ToLower();

            }

            this.RefreshCapsText();

        }

        List<T> FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            List<T> collecion = new List<T>();

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);

                if (child != null && child is T)
                    collecion.Add((T)child);
                else
                {
                    collecion.AddRange(FindVisualChild<T>(child));
                }
            }

            return collecion;
        }

        private void btn_caps_Click(object sender, RoutedEventArgs e)
        {
            FuncButtonControl btn = sender as FuncButtonControl;

            string tag = btn.Tag.ToString();

            byte b = Convert.ToByte(tag);

            KeyHelper.OnKeyDown(b);

            btn.IsChecked = !btn.IsChecked;

            this.RefreshCaps();
        }

        private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.OnCancelClick();
        }


        /// <summary>
        /// 回车确认功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Enter_OnClick(object sender, RoutedEventArgs e)
        {


            var text = this.txtValue.Text;

            txtValueToMain = text;

            if (inputtxt.GetType().Equals(typeof(TextBox)))
            {
                ((TextBox)inputtxt).Text = text;
                Keyboard.ClearFocus();
            }
            else if (inputtxt.GetType().Equals(typeof(PasswordBox)))
            {
                ((PasswordBox)inputtxt).Password = text;
                Keyboard.ClearFocus();

            }

            this.Focus();
            Keyboard.ClearFocus();
            this.Close();
        }
    }

}

